//! 测试工具函数
//!
//! 提供测试隔离、临时文件管理等辅助功能。

#![allow(dead_code)]

use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, Ordering};

/// 全局测试计数器，用于生成唯一标识
static TEST_COUNTER: AtomicU32 = AtomicU32::new(0);

/// 生成唯一的测试 ID
pub fn unique_test_id() -> String {
    let id = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
    format!("test_{}", id)
}

/// 临时测试目录管理器
pub struct TempTestDir {
    path: PathBuf,
}

impl TempTestDir {
    /// 创建新的临时测试目录
    pub fn new(prefix: &str) -> std::io::Result<Self> {
        let dir_name = format!("{}_{}", prefix, unique_test_id());
        let path = std::env::temp_dir().join("log4r_tests").join(dir_name);
        std::fs::create_dir_all(&path)?;
        Ok(Self { path })
    }

    /// 获取目录路径
    pub fn path(&self) -> &PathBuf {
        &self.path
    }

    /// 在目录中创建文件
    pub fn create_file(&self, name: &str, content: &str) -> std::io::Result<PathBuf> {
        let file_path = self.path.join(name);
        std::fs::write(&file_path, content)?;
        Ok(file_path)
    }
}

impl Drop for TempTestDir {
    fn drop(&mut self) {
        // 清理临时目录
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

/// 测试配置生成器
pub struct TestConfigBuilder {
    level: String,
    appenders: Vec<String>,
}

impl Default for TestConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TestConfigBuilder {
    /// 创建新的配置生成器
    pub fn new() -> Self {
        Self {
            level: "INFO".to_string(),
            appenders: Vec::new(),
        }
    }

    /// 设置日志级别
    pub fn level(mut self, level: &str) -> Self {
        self.level = level.to_string();
        self
    }

    /// 添加控制台 Appender
    pub fn with_console(mut self) -> Self {
        self.appenders.push("console".to_string());
        self
    }

    /// 添加文件 Appender
    pub fn with_file(mut self, path: &str) -> Self {
        self.appenders.push(format!("file:{}", path));
        self
    }

    /// 生成 TOML 配置字符串
    pub fn build_toml(&self) -> String {
        let mut config = format!(
            r#"# 测试配置
[log4r]
level = "{}"
"#,
            self.level
        );

        if self.appenders.contains(&"console".to_string()) {
            config.push_str(
                r#"
[appenders.console]
type = "console"
target = "stdout"
"#,
            );
        }

        for appender in &self.appenders {
            if let Some(path) = appender.strip_prefix("file:") {
                config.push_str(&format!(
                    r#"
[appenders.file]
type = "file"
path = "{}"
"#,
                    path
                ));
            }
        }

        config
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_unique_test_id() {
        let id1 = unique_test_id();
        let id2 = unique_test_id();
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_temp_test_dir() {
        let dir = TempTestDir::new("test").expect("创建临时目录失败");
        assert!(dir.path().exists());

        let file_path = dir.create_file("test.txt", "hello").expect("创建文件失败");
        assert!(file_path.exists());
    }

    #[test]
    fn test_config_builder() {
        let config = TestConfigBuilder::new()
            .level("DEBUG")
            .with_console()
            .build_toml();

        assert!(config.contains("level = \"DEBUG\""));
        assert!(config.contains("[appenders.console]"));
    }
}
